package org.liang.code.jms.topic;

import jakarta.jms.JMSContext;
import jakarta.jms.JMSProducer;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;
import org.liang.code.utils.jms.JMSCommons;

import java.util.concurrent.CountDownLatch;

/**
 * 主题发布者
 */
@Slf4j
public class TPublisher implements Runnable{

    private final CountDownLatch latch;
    private final ActiveMQJMSConnectionFactory factory;

    public TPublisher(CountDownLatch latch, ActiveMQJMSConnectionFactory factory) {
        this.latch = latch;
        this.factory = factory;
    }

    @Override
    public void run() {

        // 创建JMSContext
        JMSContext context = factory.createContext(Session.AUTO_ACKNOWLEDGE);
        // 创建发布者
        JMSProducer producer = context.createProducer();
        String body = JMSCommons.counter.getAndAdd(1) + "";
        TextMessage message = context.createTextMessage(body);
        // 发布消息
        producer.send(context.createTopic(JMSCommons.CORE_TOPIC), message);
        log.info("发布消息：{}", body);
        context.close();
        latch.countDown();
    }
}
